#!/bin/bash
# update variables for bash 
# vupdate <VarName> <VarValue>
# Input:
#	VarName: name of path variable
#	VarValue: string, path, if empty, set to current working directory.
# Author: sid chen(cnqdcyq@163.com)
# Date: 2022/2/13

# ideas:
# 1. if file exist
#	no: create -> node 2
# 2. exist, if has <VarName>
#	no: add <VarName> to tail -> node 3
# 3. has <VarName>, use `sed` to change <VarValue>
#
# Log:
#	2022/2/9	ver1.0 create
#	2022/2/13 	ver1.1 modify,sed find pattern change "/" to "#"

FileExport="$HOME/.bash/.bash_export"
####### function define ########
check_export_list () {
# if exist file, return 1
# if not,create and return 1 
	if [[ -f $FileExport ]]; then
		true
	else
		echo "file .bash_export created!"
		touch $FileExport
	fi
	return 1
}

check_has_variable () {
	case $(grep -c "$VarName" "$FileExport") in
		0 )
			echo "$VarName not exit "
			return 2 
			;;
		1 )
			return 1
			;;
		* )
			echo "There are different options!"
			grep "$VarName" "$FileExport"
			echo "Continue to modify?(y or n)"
			read choice
			case $choice in
				yes|y|Y|Yes|YES )
					return 1
					;;
				no|n|N|No|NO )
					return 3
					;;
				* )
					return -1
					;;
			esac
		esac
}

add_variable () {
	echo "add or not? (yes or no)"
	read choice
	case $choice in
		yes|y|Y|Yes|YES )
			echo "add variable: $VarName" &&\
				echo "export $VarName=$VarValue" >> $FileExport &&\
				return 1
			;;
		no|n|N|No|NO )
			return -1
			;;
	esac
}

change_variable_value () {
	NewString="export $VarName=$VarValue" \
		&& sed -i "/$VarName=/c $NewString" $FileExport \
		&& return 0
	return 1
}

show_help () {
	echo ""
	echo "vupdate.sh [-h|-d|-l] <Key> <Value>"
}

show_list () {
	if [[ -f $FileExport ]];then
		cat $FileExport
	else
		echo ".bash_export not exist!"
	fi
}
delete_variable () {
	sed -i "/$1/d" $FileExport
	unset $1
}
######## parameters ########
case "$1" in
	-h|"" ) 
		show_help
		return 0
		;;
	-l ) 
		show_list
		return 0
		;;
	-d )
		delete_variable "$2" && return 0;;
	-u )
		source ~/.bash/.bash_export && return 0
		;;
esac

######## constant define ########
VarName="$1"
VarValue="$2"


######## main part ########

# check whether set $2
if [ "$VarValue" = "" ];then
	echo "set VarValue to current working dir"
	VarValue="$(pwd)"
fi

# check whether .bash_export exit
check_export_list
if [ "$?" = "1" ];then
	check_has_variable
else
	exit 1
fi

case $? in
	1 )
		change_variable_value && echo "change variable value"
		;;
	2 )
		add_variable
		;;
	3 )
		return 1
		;;
	* )
		exit 1
esac

export $VarName=$VarValue



